package com.ruoyi.product.service.impl;

import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.baseData.domain.dto.WoProceduresDto;
import com.ruoyi.baseData.domain.vo.ProcessRelVo;
import com.ruoyi.baseData.domain.vo.WoProceduresVo;
import com.ruoyi.baseData.service.ProceduresEquipmentConfigService;
import com.ruoyi.baseData.service.ProceduresService;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.product.domain.*;

import com.ruoyi.product.domain.dto.WoOpLogDto;
import com.ruoyi.product.domain.dto.WoSubRawDto;
import com.ruoyi.product.mapper.*;

import com.ruoyi.product.service.WoOpLogService;
import com.ruoyi.product.service.WoSubRawService;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
public class WoRawRelServiceImpl implements WoSubRawService {

    @Resource
    WoSubMapper woRawSubMapper;


    @Resource
    WoRawMapper woRawMapper;


    @Resource
    WoSubRawMapper woRawRelMapper;

    @Resource
    WorkOrderMapper workOrderMapper;

    /**
     * 工单工序处理
     */
    @Resource
    ProceduresService proceduresService;

    /**
     * 工单的日志服务
     */
    @Resource
    WoOpLogService woOpLogService;

    /**
     * 工单操作记录
     */
    @Resource
    WoOpLogMapper woOpLogMapper;


    @Resource
    ProceduresEquipmentConfigService proceduresEquipmentConfigService;

    @Override
    public void addWoSubRaw(WoSubRawDto woSubRawDto) {


        MPJLambdaWrapper<WorkOrder> wrapper = new MPJLambdaWrapper<WorkOrder>()
                .eq(WorkOrder::getWo, woSubRawDto.getWo())
                .ne(WorkOrder::getDelFlag, 1);

        WorkOrder workOrder = workOrderMapper.selectOne(wrapper);

        if(null == workOrder) {
            throw new GlobalException("没有该工单请重新查询");
        }

        Integer maxCount = workOrder.getMaxCount() + 1;
        StringBuilder stringBuilder = new StringBuilder();
        //2位数
        stringBuilder.append(String.format("%02d",Integer.valueOf(maxCount)));


        //1.生成子卷信息(注意校验是否重复)
        String userName = SecurityUtils.getUsername();
        WoSub test2 = new WoSub();
        /**
         * 获取长度 子卷信息
         */

        test2.setLength(woSubRawDto.getLength());
        test2.setWo(woSubRawDto.getWo());
        test2.setDelFlag(false);
        test2.setCreateBy(userName);
        test2.setCreateTime(new Date());
        test2.setSerialNo(workOrder.getBatchCode() + stringBuilder.toString());
        woRawSubMapper.insert(test2);


        /**
         * 工单信息更新
         */
        workOrder.setMaxCount(maxCount);
        workOrderMapper.updateById(workOrder);
        //2.根据工单号查询原材料


        //1.增加工作记录
        WoOpLogDto woOpLogDto = new WoOpLogDto();






        MPJLambdaWrapper<WoRaw> wrapper2 = new MPJLambdaWrapper<WoRaw>()
                .selectAll(WoRaw.class)//查询user表全部字段
                //记的测试阶段
                .eq(WoRaw::getDelFlag, 0)
                .eq(WoRaw::getWo, woSubRawDto.getWo())
                .eq(WoRaw::getStatus, "未消耗");
        List<WoRaw> woRaws = woRawMapper.selectList(wrapper2);

        //3.生成关系表(批量插入)
        for(WoRaw woRaw: woRaws) {
            WoSubRaw woRawRel = new WoSubRaw();
            woRawRel.setDelFlag(false);
            woRawRel.setCreateBy(userName);
            woRawRel.setCreateTime(new Date());
            woRawRel.setWoRawId(woRaw.getId());
            woRawRel.setWoRawSubId(test2.getId());
            woRawRelMapper.insert(woRawRel);
        }
    }

    /**
     * 工单开工提交
     * @param woSubRawDto
     */
    @Override
    public void startWoRaw(WoSubRawDto woSubRawDto) {
        MPJLambdaWrapper<WorkOrder> wrapper = new MPJLambdaWrapper<WorkOrder>()
                .eq(WorkOrder::getWo, woSubRawDto.getWo())
                .ne(WorkOrder::getDelFlag, 1);
        WorkOrder workOrder = workOrderMapper.selectOne(wrapper);
        if(null == workOrder) {
            throw new GlobalException("没有该工单请重新查询");
        }
        if("已开工".equals(workOrder.getStatus()) ) {
//        if("已开工".equals(workOrder.getStatus()) && !"涂布".equals(workOrder.getType())) {
            throw new GlobalException("该工单已经开工");
        }

        Integer maxCount = workOrder.getMaxCount() + 1;
        StringBuilder stringBuilder = new StringBuilder();
        //2位数
        stringBuilder.append(String.format("%02d",Integer.valueOf(maxCount)));

        /**
         * 子卷任务
         */
        String userName = SecurityUtils.getUsername();
        /**
         * 第四道生成子卷
         */
        if("涂布".equals(workOrder.getType())) {
            //第四步开工才能生成记录数量
            if(workOrder.getProceduresNum() == 4) {
                //这个不需要
//                MPJLambdaWrapper<WoSub> wrapper2 = new MPJLambdaWrapper<WoSub>()
//                        .selectAll(WoSub.class)//查询user表全部字段
//                        //记的测试阶段
//                        .isNull(WoSub::getLength)
//                        .eq(WoSub::getWo, woSubRawDto.getWo())
//                        .eq(WoSub::getDelFlag, 0);
//
//                WoSub woRawSub = woRawSubMapper.selectOne(wrapper2);
//                if(woRawSub != null) {
//                    throw new GlobalException("工单已经开工");
//                }
                //1.生成子卷信息(注意校验是否重复)

                WoSub test2 = new WoSub();
                /**
                 * 获取长度 子卷信息
                 */
                test2.setLength(woSubRawDto.getLength());
                test2.setWo(woSubRawDto.getWo());
                test2.setDelFlag(false);
                test2.setCreateBy(userName);
                test2.setCreateTime(new Date());
                test2.setSerialNo(workOrder.getWo() + "-" + stringBuilder.toString());
                woRawSubMapper.insert(test2);
            }
            workOrder.setMaxCount(maxCount);
            workOrder.setStatus("已开工");
            workOrder.setStartTime(new Date());
            workOrderMapper.updateById(workOrder);



        } else if("分切".equals(workOrder.getType())) {
            workOrder.setStartTime(new Date());
            workOrder.setStatus("已开工");
            workOrderMapper.updateById(workOrder);
        } else if("预混".equals(workOrder.getType())) {
            workOrder.setStartTime(new Date());
            workOrder.setStatus("已开工");
            workOrderMapper.updateById(workOrder);
        } else {
            workOrder.setStartTime(new Date());
            workOrder.setStatus("已开工");
            workOrderMapper.updateById(workOrder);
        }
        WoOpLog woOpLog = new WoOpLog();
        woOpLog.setWo(workOrder.getWo());
        woOpLog.setStartTime(new Date());
        woOpLog.setProceduresNum(workOrder.getProceduresNum());
        woOpLog.setDelFlag(false);
        woOpLog.setCreateBy(userName);
        woOpLog.setCreateTime(new Date());
        woOpLog.setWoType(workOrder.getType());
        woOpLog.setStatus("已开工");
        woOpLogMapper.insert(woOpLog);



    }

    /**
     * 插入子卷的号
     * @param woSubRawDto
     */
    @Override
    public void insertWoRawRel(WoSubRawDto woSubRawDto) {
        MPJLambdaWrapper<WorkOrder> wrapper = new MPJLambdaWrapper<WorkOrder>()
                .eq(WorkOrder::getWo, woSubRawDto.getWo())
                .ne(WoSub::getDelFlag, 1);


        WorkOrder workOrder = workOrderMapper.selectOne(wrapper);

        if(null == workOrder) {
            throw new GlobalException("没有该工单请重新查询");
        }

        /**
         * 查询空值
         */

        if("涂布".equals(workOrder.getType())) {
            MPJLambdaWrapper<WoSub> wrapper2 = new MPJLambdaWrapper<WoSub>()
                    .selectAll(WoSub.class)//查询user表全部字段
                    //记的测试阶段
                    .eq(WoSub::getWo, woSubRawDto.getWo())
                    .isNull(WoSub::getLength)
                    .eq(WoSub::getDelFlag, 0);

            WoSub woRawSub = woRawSubMapper.selectOne(wrapper2);

            if(null == woRawSub ) {
                throw new GlobalException("需要点击开工");
            }
            String userName = SecurityUtils.getUsername();
            woRawSub.setLength(woSubRawDto.getLength());
            woRawSub.setRawType(woSubRawDto.getRawType());
            woRawSub.setUpdateBy(userName);
            woRawSub.setUpdateTime(new Date());
            woRawSubMapper.updateById(woRawSub);

            //2.根据工单号查询原材料
            MPJLambdaWrapper<WoRaw> wrapper3 = new MPJLambdaWrapper<WoRaw>()
                    .selectAll(WoRaw.class)//查询user表全部字段
                    //记的测试阶段
                    .eq(WoRaw::getDelFlag, 0)
                    .eq(WoRaw::getWo, woSubRawDto.getWo())
                    .eq(WoRaw::getStatus, "未消耗");
            List<WoRaw> woRaws = woRawMapper.selectList(wrapper3);

            //3.生成关系表(批量插入)
            for(WoRaw woRaw: woRaws) {
                WoSubRaw woRawRel = new WoSubRaw();
                woRawRel.setDelFlag(false);
                woRawRel.setCreateBy(userName);
                woRawRel.setCreateTime(new Date());
                woRawRel.setWoRawId(woRaw.getId());
                woRawRel.setWoRawSubId(woRawSub.getId());
                woRawRelMapper.insert(woRawRel);
            }
            Integer maxCount = workOrder.getMaxCount() + 1;
            StringBuilder stringBuilder = new StringBuilder();
            //2位数
            stringBuilder.append(String.format("%02d",Integer.valueOf(maxCount)));
            workOrder.setMaxCount(maxCount);
            workOrderMapper.updateById(workOrder);
            WoSub test2 = new WoSub();
            /**
             * 获取长度 子卷信息
             */
//        test2.setLength(woRawRelDto.getLength());
            test2.setWo(woSubRawDto.getWo());
            test2.setDelFlag(false);
            test2.setCreateBy(userName);
            test2.setCreateTime(new Date());
            test2.setSerialNo(workOrder.getWo() + "-" + stringBuilder.toString());
            woRawSubMapper.insert(test2);
        } else if("分切".equals(woSubRawDto.getType())) {
//            MPJLambdaWrapper<WoRawSub> wrapper2 = new MPJLambdaWrapper<WoRawSub>()
//                    .selectAll(WoRawSub.class)//查询user表全部字段
//                    //记的测试阶段(
//                    .eq(WoRawSub::getWo,woRawRelDto.getWo())
//                    .isNull(WoRawSub::getLength)
//                    .eq(WoRawSub::getDelFlag, 0);
//            List<WoRawSub> woRawSubs = woRawSubMapper.selectJoinList(wrapper2);
//            if(null == woRawSubs || woRawSubs.size() <= 0) {
//                throw new GlobalException("请输入卷数");
//            }
            if(null == woSubRawDto.getRollNums() || woSubRawDto.getRollNums() <= 0) {
                throw new GlobalException("请先输入数量");
            }
            MPJLambdaWrapper<WoRaw> wrapper3 = new MPJLambdaWrapper<WoRaw>()
                    .selectAll(WoRaw.class)//查询user表全部字段
                    //记的测试阶段
                    .eq(WoRaw::getDelFlag, 0)
                    .eq(WoRaw::getWo, woSubRawDto.getWo())
                    .eq(WoRaw::getStatus, "未消耗");
            List<WoRaw> woRaws = woRawMapper.selectList(wrapper3);

            String userName = SecurityUtils.getUsername();
            Integer maxCount = workOrder.getMaxCount();
            Integer maxResultCount = workOrder.getMaxCount() + woSubRawDto.getRollNums();
            for(Integer i = 1; i <= woSubRawDto.getRollNums(); i++) {
                maxCount = maxCount + 1;
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(String.format("%02d",Integer.valueOf(maxCount)));
                WoSub woRawSub = new WoSub();
                woRawSub.setWo(woSubRawDto.getWo());
                woRawSub.setDelFlag(false);
                woRawSub.setCreateBy(userName);
                woRawSub.setCreateTime(new Date());
                woRawSub.setSerialNo(workOrder.getBatchCode() + stringBuilder.toString());
                woRawSubMapper.insert(woRawSub);
                for(WoRaw woRaw: woRaws) {
                    WoSubRaw woRawRel = new WoSubRaw();
                    woRawRel.setDelFlag(false);
                    woRawRel.setCreateBy(userName);
                    woRawRel.setCreateTime(new Date());
                    woRawRel.setWoRawId(woRaw.getId());
                    woRawRel.setWoRawSubId(woRawSub.getId());
                    woRawRelMapper.insert(woRawRel);
                }
            }

            workOrder.setMaxCount(maxResultCount);
            workOrderMapper.updateById(workOrder);
        } else {

        }
    }

    /**
     * todo:注意排序号
     * @param woSubRawDtos
     */
    @Override
    public void insertWoRawRels(List<WoSubRawDto> woSubRawDtos) {

        if(null == woSubRawDtos || woSubRawDtos.size() <= 0 ) {
            throw new GlobalException("输入数据不能为空");
        }
        WoSubRawDto woSubRawDto = woSubRawDtos.get(0);

        MPJLambdaWrapper<WorkOrder> wrapper = new MPJLambdaWrapper<WorkOrder>()
                .eq(WorkOrder::getWo, woSubRawDto.getWo())
                .ne(WoSub::getDelFlag, 1);
        WorkOrder workOrder = workOrderMapper.selectOne(wrapper);
        if(null == workOrder) {
            throw new GlobalException("没有该工单请重新查询");
        }

        if(workOrder.getType().equals("涂布") && (workOrder.getProceduresNum() ==  1
                || workOrder.getProceduresNum() ==  2
                || workOrder.getProceduresNum() ==  3
        )) {
            throw new GlobalException("涂布前三道工序不能生成子卷");
        }

        String userName = SecurityUtils.getUsername();
        MPJLambdaWrapper<WoRaw> wrapper3 = new MPJLambdaWrapper<WoRaw>()
                .selectAll(WoRaw.class)//查询user表全部字段
                //记的测试阶段
                .eq(WoRaw::getDelFlag, 0)
                .eq(WoRaw::getWo, woSubRawDto.getWo())
                .eq(WoRaw::getStatus, "未消耗");

        List<WoRaw> woRaws = woRawMapper.selectList(wrapper3);

        if(null == woRaws || woRaws.size() <=0) {
            throw new GlobalException("请先输入原材料");
        }

        /**
         * 查询现有的子卷数据
         */
        List<WoSub> woSubs = woRawSubMapper.selectList( new MPJLambdaWrapper<WoSub>()
                .selectAll(WoSub.class).eq(WoSub::getDelFlag, 0).eq(WoSub::getWo, woSubRawDto.getWo()).orderByAsc(WoSub::getSequence));


        for(Integer i = 0;  i< woSubs.size(); i++ ) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(String.format("%02d",Integer.valueOf(i +1)));
            woSubs.get(i).setSerialNo(workOrder.getWo() + "-" + stringBuilder.toString());
            woRawSubMapper.updateById(woSubs.get(i));
//            woSub.setSerialNo(workOrder.getWo() + "-" + stringBuilder.toString());
        }


        /**
         * 生成最大值
         */
        Integer maxCount = workOrder.getMaxCount();
        Integer maxResultCount = workOrder.getMaxCount() + woSubRawDtos.size();
        Integer tatolCount =woSubs !=null && woSubs.size() > 0 ? woSubs.size() : 0;
//        Integer tatolResultCount = tatolCount + woSubRawDtos.size();
        for(WoSubRawDto item:woSubRawDtos) {
            maxCount = maxCount + 1;
            tatolCount = tatolCount + 1;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(String.format("%02d",Integer.valueOf(tatolCount)));
            WoSub woSub = new WoSub();
            woSub.setWo(item.getWo());
            woSub.setLength(item.getLength());
            woSub.setDelFlag(false);
            woSub.setCreateBy(userName);
            woSub.setCreateTime(new Date());
            woSub.setMaterialCode(workOrder.getMaterialCode()); //添加物料号
            woSub.setSerialNo(workOrder.getWo() + "-" + stringBuilder.toString());
            woSub.setSequence(maxCount); //内部序列号
            woRawSubMapper.insert(woSub);
            /**
             * 关系图
             */

            for(WoRaw woRaw: woRaws) {
                WoSubRaw woRawRel = new WoSubRaw();
                woRawRel.setDelFlag(false);
                woRawRel.setCreateBy(userName);
                woRawRel.setCreateTime(new Date());
                woRawRel.setWoRawId(woRaw.getId());
                woRawRel.setWoRawSubId(woSub.getId());
                woRawRelMapper.insert(woRawRel);
            }
        }
        workOrder.setMaxCount(maxResultCount);
        workOrderMapper.updateById(workOrder);
    }

    @Override
    public void endWoRaw(WoSubRawDto woSubRawDto) {
        String userName = SecurityUtils.getUsername();
        MPJLambdaWrapper<WorkOrder> wrapper3 = new MPJLambdaWrapper<WorkOrder>()
                .selectAll(WorkOrder.class)//查询user表全部字段
                //记的测试阶段
                .eq(WoSub::getWo, woSubRawDto.getWo())
                .ne(WoSub::getDelFlag, 1);
        /**
         * 记得到下一个环节
         */
        WorkOrder workOrder = workOrderMapper.selectOne(wrapper3);
        if(null == workOrder) {
            throw new GlobalException("没有该工单请重新查询");
        }
            /**
             * 工单完工状态
             */
        if("已完工".equals(workOrder.getStatus())) {
            throw new GlobalException("该工单已完工");
        }
        if(null != workOrder) {
            /**
             * 检查是否具有WoSub的数据(涂布工序1和2不需要考虑批次记录(不做处理)
             */
            if(workOrder.getType().equals("涂布")
                    && (workOrder.getProceduresNum() == 1 ||workOrder.getProceduresNum() ==2 || workOrder.getProceduresNum() ==3  )) {

            } else {
                MPJLambdaWrapper<WoSub> wrapper2 = new MPJLambdaWrapper<WoSub>()
                        .selectAll(WoSub.class)//查询user表全部字段
                        //记的测试阶段
                        .eq(WoSub::getWo, woSubRawDto.getWo())
                        .eq(WoSub::getDelFlag, 0);
                List<WoSub> woSubs = woRawSubMapper.selectList(wrapper2);
                if(null == woSubs || woSubs.size() <= 0 ) {
                    throw new GlobalException("请先生成批次记录");
                }
            }
            //删除涂布4的空的子卷
            if(workOrder.getType().equals("涂布") && workOrder.getProceduresNum() == 4) {
                MPJLambdaWrapper<WoSub> wrapper2 = new MPJLambdaWrapper<WoSub>()
                        .selectAll(WoSub.class)//查询user表全部字段
                        //记的测试阶段
                        .isNull(WoSub::getLength)
                        .eq(WoSub::getWo, woSubRawDto.getWo())
                        .eq(WoSub::getDelFlag, 0);
                List<WoSub> woSubs = woRawSubMapper.selectList(wrapper2);
                for(WoSub woSub : woSubs) {
                    woRawSubMapper.deleteById(woSub);
                }
            }

            /**
             * 已经完工按钮
             */
            WoOpLog woOpLog = new WoOpLog();


            WoProceduresDto woProceduresDto = new WoProceduresDto();
            woProceduresDto.setWoType(workOrder.getType());
            woProceduresDto.setSequence(workOrder.getProceduresNum());
            WoProceduresVo woProceduresVo = proceduresEquipmentConfigService.getNextEquipAndProceduresByWo(woProceduresDto);
            ProcessRelVo processRelVo = woProceduresVo.getProcessRelVo();
            if(null == processRelVo) {
                /**
                 * 暂停
                 */
                woOpLog.setProceduresNum(workOrder.getProceduresNum());

                workOrder.setUpdateTime(new Date());
                workOrder.setEndTime(new Date());
                workOrder.setProceduresNum(0);
                workOrder.setProceduresName("");
                workOrder.setUpdateBy(userName);
                workOrder.setStatus("已完工");
                workOrderMapper.updateById(workOrder);
            } else {
                woOpLog.setProceduresNum(workOrder.getProceduresNum());

                workOrder.setUpdateTime(new Date());
                workOrder.setUpdateBy(userName);
                workOrder.setProceduresNum(processRelVo.getSequence());
                workOrder.setProceduresName(processRelVo.getProceduresName());
                workOrder.setStatus("已开工");
                workOrderMapper.updateById(workOrder);
            }
            woOpLog.setWo(workOrder.getWo());
            woOpLog.setStartTime(new Date());
//            woOpLog.setProceduresNum(workOrder.getProceduresNum());
            woOpLog.setDelFlag(false);
            woOpLog.setCreateBy(userName);
            woOpLog.setCreateTime(new Date());
            woOpLog.setWoType(workOrder.getType());
            woOpLog.setStatus("已完工");
            woOpLogMapper.insert(woOpLog);


        }


    }

    @Override
    public void pauseWoRaw(WoSubRawDto woSubRawDto) {
        String userName = SecurityUtils.getUsername();
        MPJLambdaWrapper<WorkOrder> wrapper3 = new MPJLambdaWrapper<WorkOrder>()
                .selectAll(WorkOrder.class)//查询user表全部字段
                //记的测试阶段
                .eq(WoSub::getWo, woSubRawDto.getWo())
                .ne(WoSub::getDelFlag, 1);
        /**
         * 记得到下一个环节
         */
        WorkOrder workOrder = workOrderMapper.selectOne(wrapper3);
        if(null == workOrder) {
            throw new GlobalException("没有该工单请重新查询");
        }
        /**
         * 工单完工状态
         */
        if("已完工".equals(workOrder.getStatus()) ) {
            throw new GlobalException("该工单已完工");
        }

        if("已暂停".equals(workOrder.getStatus())) {
            throw new GlobalException("该工单已经暂停");
        }



        workOrder.setUpdateTime(new Date());
        workOrder.setUpdateBy(userName);
//        workOrder.setProceduresNum(processRelVo.getSequence());
//        workOrder.setProceduresName(processRelVo.getProceduresName());
        workOrder.setStatus("已暂停");
        workOrderMapper.updateById(workOrder);

//        WoOpLog woOpLog = new WoOpLog();
        WoOpLog woOpLog = new WoOpLog();
        woOpLog.setWo(workOrder.getWo());
        woOpLog.setStartTime(new Date());
        woOpLog.setProceduresNum(workOrder.getProceduresNum());
        woOpLog.setDelFlag(false);
        woOpLog.setCreateBy(userName);
        woOpLog.setCreateTime(new Date());
        woOpLog.setWoType(workOrder.getType());
        woOpLog.setStatus("已暂停");
        woOpLogMapper.insert(woOpLog);
    }
}




